#!/bin/bash

PORT=$1  # Get the port number from the command line argument

if [ -z "$PORT" ]; then
    echo "Please specify a port number."
    exit 1
fi

# Function to check if the port is occupied
is_port_occupied() {
    lsof -i :$PORT > /dev/null
    return $?
}

# Function to kill the process using the port
kill_process_using_port() {
    PID=$(lsof -t -i :$PORT)
    if [ -n "$PID" ]; then
        for p in $PID; do
            kill -9 $p
            echo "Port $PORT was occupied, process $p killed."
        done
    else
        echo "No process found occupying port $PORT."
    fi
}

# Ensure the port is available before starting the server
ensure_port_available() {
    if is_port_occupied; then
        echo "Port $PORT is occupied, trying to kill the process using the port..."
        kill_process_using_port
    else
        echo "Port $PORT is available, proceeding to start the server."
    fi
}

# Run the check and kill if necessary
ensure_port_available
